
package system.base;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Vector;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.hitrust.gs.bean.GSProductBidBean;
import com.hitrust.gs.bean.GSProductTypeBean;
import com.hitrust.gs.dao.GSProductBidDao;
import com.hitrust.gs.dao.GSProductTypeDao;
import com.hitrust.gs.util.DefineDic;

import framework.core.*;
import system.data.*;
/*
	Author    :Wing
	CreateTime:2008-02-20 17:30:49
*/
public class InOutStatisticSrv extends IHandler
{

	public InOutStatisticSrv() 
	{
		super();
	}
/*	private void deleteInHead(DBConnection con,SrvContext context) throws Exception
	{
		String[] ids = context.getParameterValues("ids");
		InHead obj = null;
		for(int i=0;i<ids.length;i++)
		{
			obj = InHead.fetch(con,ids[i]);
			if(obj!=null) obj.delete(con);
		}
	}
	private void saveInHead(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		String id = context.getString("Id",null);
		InHead obj;
		if((id==null)||(id.equals("")))   //add
		{
			obj = InHead.fetch();
    	}
    	else                     //update
    	{
    		obj = InHead.fetch(con,id);
    	}
		InHeadPageData data = (InHeadPageData)PageData.fromForm(context,InHeadPageData.class);
		context.setValue("InHeadPageData",data);
		obj.fill(data);
		obj.save(con);
	}
*/
	private void listInOutStatistic(DBConnection con,SrvContext context,ILoginContext loginContext,String path) throws Exception
	{
	    boolean isFirst = context.getBoolean("isFirst");
	    String isFirstVisit = "false";
	    InOutStatisticSearchEvent event = (InOutStatisticSearchEvent)SearchEvent.fromForm(context,InOutStatisticSearchEvent.class);
        String []warehouseCodes = null;
        if (isFirst)
        {
            warehouseCodes = new String[]{loginContext.getLoginWarehouseCode()}; 
            isFirstVisit = "true";
        }
        else
        {
            warehouseCodes = context.getParameterValues("WarehouseCodes");
            if (warehouseCodes == null||warehouseCodes.length==0||warehouseCodes[0].equals(""))
            {
                warehouseCodes = new String[]{"--1"};
            }
            isFirstVisit = "false";
        }
        event.setWarehouseCodes(warehouseCodes);
        event.setWarehouseCodeUser(ConstDefine.getWildCard(loginContext.getLoginWarehouseCode()));
		context.setSessionValue("InOutStatisticSearchEvent",event);
		context.setNextUrl(path+"InOutStatisticList.jsp"+"?isFirstVisit="+isFirstVisit);
	}
/*	private void backInHead(DBConnection con,SrvContext context,String path) throws Exception
	{
		context.setNextUrl(path+"InHeadList.jsp");
	}
*/	
	
    //add by Wing start
    private HSSFCell createCell(HSSFWorkbook aWb, HSSFRow aRow, short column,String aValue){
        HSSFCell tCell = aRow.createCell(column);
        tCell.setEncoding(HSSFCell.ENCODING_UTF_16);
        tCell.setCellValue(aValue);
        return tCell;
    }
    
    private void exportInOutStatistic(DBConnection con,SrvContext context,String path) throws Exception
    {
        HSSFWorkbook tWb = new HSSFWorkbook();
        HSSFSheet tSheet = tWb.createSheet();
        tWb.setSheetName(0,"产品期间出入库统计",HSSFCell.ENCODING_UTF_16);
        HSSFRow tRow = tSheet.createRow((short)0);
        HSSFCell tCell0  = createCell(tWb,tRow,(short)0, "产品编码");
        HSSFCell tCell1  = createCell(tWb,tRow,(short)1, "产品名称");
        HSSFCell tCell2  = createCell(tWb,tRow,(short)2, "单位");
        HSSFCell tCell3  = createCell(tWb,tRow,(short)3, "规格");
        HSSFCell tCell4  = createCell(tWb,tRow,(short)4, "型号");
        HSSFCell tCell5  = createCell(tWb,tRow,(short)5, "品牌");
        HSSFCell tCell6  = createCell(tWb,tRow,(short)6, "供应商");
        HSSFCell tCell7 = createCell(tWb,tRow,(short)7,"图件号");
        HSSFCell tCell8 = createCell(tWb,tRow,(short)8,"单价");
        HSSFCell tCell9  = createCell(tWb,tRow,(short)9, "入库数量");
        HSSFCell tCell10 = createCell(tWb,tRow,(short)10,"入库金额");
        HSSFCell tCell11 = createCell(tWb,tRow,(short)11,"出库数量");
        HSSFCell tCell12 = createCell(tWb,tRow,(short)12,"出库成本");
        HSSFCell tCell13 = createCell(tWb,tRow,(short)13,"区域");
        HSSFCell tCell14 = createCell(tWb,tRow,(short)14,"分类");
       
        
        InOutStatisticSearchEvent event = (InOutStatisticSearchEvent)context.getSessionValue("InOutStatisticSearchEvent");
        event.setPageSize(Value.NULL_INT);
        event.setPageNum(1);
        /** 提取  开始*/
        ObjectList list = InOutStatistic.fetch().detailqueryGroupForInit(con,event,"false");
        /** 提取  结束*/
        InOutStatisticSearchClass.FirstForm moneyForm = (InOutStatisticSearchClass.FirstForm)list.get(list.size()-1);     
        InOutStatisticSearchClass iossc = new InOutStatisticSearchClass();
        String in_money = String.valueOf(moneyForm.inMoney)== null ? "0" : String.valueOf(moneyForm.inMoney);
        String out_money = String.valueOf(moneyForm.outMoney)==null ? "0" : String.valueOf(moneyForm.outMoney);
        String storage_money = String.valueOf(moneyForm.nowMoney)==null ? "0" : String.valueOf(moneyForm.nowMoney);
        int size = list.size();
        size--;
        for(int i=0;i<size;i++)
        {
            UniversalRow lRow = (UniversalRow)list.get(i);
            HSSFRow row = tSheet.createRow((short)i+1);
            HSSFCell cell0  = createCell(tWb,row,(short)0, lRow.getString("PRODUCT_CODE")==null ? "" : lRow.getString("PRODUCT_CODE") );
            HSSFCell cell1  = createCell(tWb,row,(short)1, lRow.getString("PRODUCT_NAME")==null ? "" : lRow.getString("PRODUCT_NAME"));
            HSSFCell cell2  = createCell(tWb,row,(short)2, lRow.getString("PRODUCT_UNIT")==null ? "" : lRow.getString("PRODUCT_UNIT"));
            HSSFCell cell3  = createCell(tWb,row,(short)3, lRow.getString("SPEC")==null ? "" : lRow.getString("SPEC"));
            HSSFCell cell4  = createCell(tWb,row,(short)4, lRow.getString("MODEL")==null ? "" : lRow.getString("MODEL"));
            HSSFCell cell5  = createCell(tWb,row,(short)5, lRow.getString("PRODUCT_BRAND")==null ? "" : lRow.getString("PRODUCT_BRAND"));
            HSSFCell cell6  = createCell(tWb,row,(short)6, lRow.getString("PROVIDER_NAME")==null ? "" : lRow.getString("PROVIDER_NAME"));
            
            String tujianhao="";
            if(lRow.getString("PRODUCT_CODE")!=null ){
                Product pro = Product.fetchByConcentricityCode(con,lRow.getString("PRODUCT_CODE"));
                tujianhao = pro.getDrawingPieceCode();
                GSProductTypeDao typeDao = new GSProductTypeDao();
                GSProductTypeBean bean = typeDao.findProductTypeByProuductCodeNoStauts(pro.getConcentricityCode().trim());
                if(bean==null){
                	HSSFCell cell13 = createCell(tWb,row,(short)13,"");
                }else{
                	HSSFCell cell13 = createCell(tWb,row,(short)13,DefineDic.getProductType(bean.getProductType()+""));
                }
                GSProductBidDao bidDao = new GSProductBidDao();
                GSProductBidBean bidBean = bidDao.findProductBidByProuductCode(pro.getConcentricityCode().trim());
                if(bidBean!=null){
                	HSSFCell cell14 = createCell(tWb,row,(short)14,DefineDic.getProductBid(bidBean.getProductType()+""));
                }
            }
            HSSFCell cell7 = createCell(tWb,row,(short)7,tujianhao);
            HSSFCell cell8 = createCell(tWb,row,(short)8,lRow.getString("PRODUCT_PRICE")=="0" ? "0": lRow.getString("PRODUCT_PRICE"));
            double inCount = Double.parseDouble(lRow.getString("IN_COUNT")=="0" ? "0" : lRow.getString("IN_COUNT"));
            double outCount = Double.parseDouble(lRow.getString("OUT_COUNT") == "0" ? "0" : lRow.getString("OUT_COUNT"));
            double finalCount = Double.parseDouble(lRow.getString("FINAL_MONEY") == "0" ? "0" :lRow.getString("FINAL_MONEY"));
            double showFinalCount = finalCount + outCount - inCount;
            double inMoney = Double.parseDouble(lRow.getString("IN_MONEY")=="0" ? "0" : lRow.getString("IN_MONEY"));
            double outMoney = Double.parseDouble(lRow.getString("OUT_MONEY") == "0" ? "0" :lRow.getString("OUT_MONEY"));
            double finalMoney = Double.parseDouble(lRow.getString("FINAL_MONEY") == "0" ? "0":lRow.getString("FINAL_MONEY"));
            double showFinalMoney = finalMoney + outMoney - inMoney;
            HSSFCell cell9 = createCell(tWb,row,(short)9, StringUtil.showCount(String.valueOf(inCount)));
            HSSFCell cell10 = createCell(tWb,row,(short)10, StringUtil.showPrice(String.valueOf(inMoney)));
            HSSFCell cell11 = createCell(tWb,row,(short)11, StringUtil.showCount(String.valueOf(outCount)));
            HSSFCell cell12 = createCell(tWb,row,(short)12, StringUtil.showPrice(String.valueOf(outMoney)));

            //郑斌    2008-03-21 10:07    end
        }
        for (int i = 0; i < 3; i++) {
            //总合计
            HSSFRow row = tSheet.createRow((short)list.size()+1);
            HSSFCell cell0 = createCell(tWb,row,(short)0,"");
            HSSFCell cell1 = createCell(tWb,row,(short)1,"");
            HSSFCell cell2 = createCell(tWb,row,(short)2,"");
            HSSFCell cell3 = createCell(tWb,row,(short)3,"");
            HSSFCell cell4 = createCell(tWb,row,(short)4,"");
            HSSFCell cell5 = createCell(tWb,row,(short)5,"");
            HSSFCell cell6 = createCell(tWb,row,(short)6,"");
            HSSFCell cell7 = createCell(tWb,row,(short)7,"入库金额合计");
            HSSFCell cell8 = createCell(tWb,row,(short)8,StringUtil.showPrice(in_money));
            HSSFCell cell9 = createCell(tWb,row,(short)9,"出库成本合计:");
            HSSFCell cell10 = createCell(tWb,row,(short)10,StringUtil.showPrice(out_money));
            HSSFCell cell11 = createCell(tWb,row,(short)11,"");
            HSSFCell cell12 = createCell(tWb,row,(short)12,"");
            HSSFCell cell13 = createCell(tWb,row,(short)13,"");
            HSSFCell cell14 = createCell(tWb,row,(short)14,"");
            HSSFCell cell15 = createCell(tWb,row,(short)15,"");
            HSSFCell cell16 = createCell(tWb,row,(short)16,"");
            HSSFCell cell17 = createCell(tWb,row,(short)17,"");
            HSSFCell cell18 = createCell(tWb,row,(short)18,"");
        }
        
        
        DateUtil date = new DateUtil();
        String year = date.getYear() + "";
        String month = date.getMonth() + "";
        if (date.getMonth() < 10) month = "0" + date.getMonth();
        String day = date.getDay() + "";
        if (date.getDay() < 10) day = "0" + date.getDay();
        String hour = date.getHour() + "";
        if (date.getHour() < 10) hour = "0" + date.getHour();
        String minute = date.getMinute() + "";
        if (date.getMinute() < 10) minute = "0" + date.getMinute();
        String second = date.getSecond() + "";
        if (date.getSecond() < 10) second = "0" + date.getSecond();
        
        String fileName = "OUT_BILL_" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_" + second + ".xls";
        context.m_res.setContentType("application/ms-excel");
        context.m_res.addHeader("Content-disposition", "filename="+fileName);
        ServletOutputStream out = context.getServletOutputStream();
        tWb.write(out);
    }

    //add by Wing end
	
	public void doAction(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		String action_code = context.getActionCode();
		String path = "/system/base/";
		
		if(action_code.equalsIgnoreCase("listInOutStatistic"))
		{
            ObjectList warehouseList = Warehouse.fetchAllOrgsByShow(con, loginContext.getLoginWarehouseCode());
            context.setSessionValue("WarehouseListDetail", warehouseList);
            listInOutStatistic(con,context,loginContext,path);
			return;
		}
/*		if(action_code.equalsIgnoreCase("viewInHead"))
		{
			String id = context.getString("Id",null);
			InHead obj = InHead.fetch(con,id);
			context.setValue("InHead",obj);
			context.setNextUrl(path+"InHeadView.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("deleteInHead"))
		{
			context.setErrorUrl(path+"InHeadList.jsp");
			deleteInHead(con,context);
			backInHead(con,context,path);
			return;
		}
			
		if(action_code.equalsIgnoreCase("toAddInHead"))
		{
			InHead obj = InHead.fetch();
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("toUpdateInHead"))
		{
			String id = context.getString("Id",null);
			InHead obj = InHead.fetch(con,id);
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("toCopyInHead"))
		{
			String id = context.getString("Id",null);
			InHead obj = InHead.copy(InHead.fetch(con,id));
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("saveInHead"))
		{
			context.setErrorUrl(path+"InHeadEdit.jsp");
			saveInHead(con,context,loginContext);
			backInHead(con,context,path);
			return;
		}
		if(action_code.equalsIgnoreCase("saveAndNewInHead"))
		{
			context.setErrorUrl(path+"InHeadEdit.jsp");
			saveInHead(con,context,loginContext);
			InHead obj = InHead.fetch();
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");			
			return;
		}
		if(action_code.equalsIgnoreCase("backListInHead"))
		{
			backInHead(con,context,path);
			return;
		}
*/		
		//add by Wing start
		if(action_code.equalsIgnoreCase("exportInOutStatistic"))
        {
		    exportInOutStatistic(con,context,path);
            return;
        }
		//add by Wing end

		Logger.throwException("InOutStatisticSrv","unknown action_code="+action_code);
	}
}
